#include "app_message.h"
#include "cjson/cJSON.h"
#include "string.h"
#include "log/log.h"
#include "app_common.h"
int app_message_json2chars(char *json, char *data_buf, int buf_len)
{
    //解析json字符串
    cJSON *root = cJSON_Parse(json);
    // if (root == NULL)
    // {
    //     return -1;
    // }
    int conn_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root, "msg")->valuestring;
    int id_len;
    int msg_len;
    //转换16进制字符串id_hexstr、msg_hexstr为字符串
    char *id = app_common_hexstr2chars(id_hexstr, &id_len);
    char *msg = app_common_hexstr2chars(msg_hexstr, &msg_len);
    int  len = 3 + id_len + msg_len;
    if (len > buf_len)
    {
        log_debug("data_buf大小不够");
        free(id);
        free(msg);
        return -1;
    }
    //拼接字符串写入data_buf
    data_buf[0] = conn_type;
    data_buf[1] = id_len;
    data_buf[2] = msg_len;
    memcpy(data_buf + 3, id, id_len);
    memcpy(data_buf + 3 + id_len, msg, msg_len);
    //释放内存
    cJSON_Delete(root);
    free(id);
    free(msg);
    //返回写入的长度
    return len;
}

char *app_message_chars2json(char *data, int len)
{
    //解析字符串data,提取conn_type, id_len, msg_len, id, msg
    int conn_type = data[0];
    int id_len = data[1];
    int msg_len = data[2];
    char id[id_len];
    char msg[msg_len];
    memcpy(id, data + 3, id_len);
    memcpy(msg, data + 3 + id_len, msg_len);


    //将id和message转换为对应16进制字符串
    char *id_hexstr = app_common_chars2hexstr(id, id_len);
    char *msg_hexstr = app_common_chars2hexstr(msg, msg_len);

    //拼接json
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hexstr);
    cJSON_AddStringToObject(root, "msg", msg_hexstr);
    char *json = cJSON_PrintUnformatted(root);
    //释放内存
    cJSON_Delete(root);
    free(id_hexstr);
    free(msg_hexstr);
    //返回json字符串
    return json;
}
